﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Navigation;
using System.Collections.Generic;
using System.Windows.Threading;

namespace TMTemplate
{
    public partial class Root : UserControl
    {
        public Root()
        {
            InitializeComponent();
            VisualStateManager.GoToState(this, "Loading", false);
            this.Loaded += new System.Windows.RoutedEventHandler(MainPage_Loaded);
            PageManager.This.PageChanged += new PageManager.PageManagerEventHandler(This_PageChanged);
            this.Splash.Storyboard.Completed += new EventHandler((s, e) =>
            {
                splashAnimationCompleted = true;
            });
        }

        void This_PageChanged(PageManager.PageManagerEventArgs e)
        {
            pageSound.Stop();
            pageSound.Position = new TimeSpan();
            pageSound.Play();
            if (States.CurrentState.Name == "Splash" && splashAnimationCompleted)
            {
                VisualStateManager.GoToState(this, "Normal", false);
                pageManager.Blank2Page.Begin();
            }
        }

        bool splashAnimationCompleted = false;

        private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 1);
            timer.Tick += new EventHandler((_s, _e) =>
            {
                VisualStateManager.GoToState(this, "Splash", false);
                timer.Stop();
                foreach (UriMapping urimapping in (pageManager.ContentPage.UriMapper as UriMapper).UriMappings)
                {
                    if (urimapping != null && (urimapping.Uri != null && System.Windows.Browser.HtmlPage.Document.DocumentUri.ToString().Contains("#" + urimapping.Uri.ToString())))
                    {
                        Splash.Storyboard.Completed += new EventHandler((_s_, _e_) =>
                        {
                            VisualStateManager.GoToState(this, "Normal", false);
                            pageManager.Blank2Page.Begin();
                        });
                    }
                }
            });
            timer.Start();
        }
    }
}